// Copyright 2012 Google Inc. All Rights Reserved.

package com.google.appengine.syncserver.shared;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.annotate.JsonCreator;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.JsonMappingException;

import java.io.IOException;
import java.util.logging.Logger;

/**
 * Response page for read page request.
 */
public class ReadUpdateResponsePage {

  private static final String LAST_PAGE = "lastPage";
  private static final String MAX_VERSION = "maxVersion";
  private static final String CHANGES = "changes";

  private static final Logger log = Logger.getLogger(ReadUpdateResponsePage.class.getName());

  /**
   * Converts serialized json string to {@link ReadUpdateResponsePage} object.
   * 
   * @param str
   * @return {@link ReadUpdateResponsePage} as read from the json string.
   */
  public static ReadUpdateResponsePage valueOf(String str)
      throws JsonParseException, JsonMappingException, IOException {
    return (ReadUpdateResponsePage) JsonUtils.stringToObject(str, ReadUpdateResponsePage.class);
  }

  // The set of updates to the client.
  private final PropertyChange[] propertyChanges;

  /**
   * Max version over all property changes this page contains.
   */
  private final long maxVersion;

  /**
   * Whether this is the last page to be sent from the server.
   */
  private final boolean lastPage;

  @JsonCreator
  public ReadUpdateResponsePage(
      @JsonProperty(CHANGES) PropertyChange[] propertyChanges,
      @JsonProperty(MAX_VERSION) long maxVersion, 
      @JsonProperty(LAST_PAGE) boolean lastPage) {
    this.propertyChanges = propertyChanges;
    this.maxVersion = maxVersion;
    this.lastPage = lastPage;
  }

  /**
   * @return The max version over all changes.
   */
  @JsonProperty(MAX_VERSION)
  public long getMaxVersion() {
    return this.maxVersion;
  }

  /**
   * @return The changes in this update response.
   */
  @JsonProperty(CHANGES)
  public PropertyChange[] getPreferenceChanges() {
    return propertyChanges;
  }

  /**
   * @return Whether the page is the last response page.
   */
  @JsonProperty(LAST_PAGE)
  public boolean isLastPage() {
    return this.lastPage;
  }

  @Override
  public String toString() {
    try {
      return JsonUtils.objectToString(this);
    } catch (JsonGenerationException e) {
      log.severe(e.getMessage());
    } catch (JsonMappingException e) {
      log.severe(e.getMessage());
    } catch (IOException e) {
      log.severe(e.getMessage());
    }
    return null;
  }
}
